<template>
  <view class="export-order">
    <!-- 导航栏 -->
    <view class="header">
      <view class="title">我的订单导出</view>
    </view>

    <!-- 时间范围选择 -->
    <view class="filter-section">
      <view class="filter-item">
        <text class="label">选择时间范围:</text>
        <view class="date-range">
          <picker mode="date" :value="startDate" @change="onStartDateChange">
            <view class="date-picker">
              <text>{{ startDate || "开始日期" }}</text>
              <text class="icon">📅</text>
            </view>
          </picker>
          <text class="to">至</text>
          <picker mode="date" :value="endDate" @change="onEndDateChange">
            <view class="date-picker">
              <text>{{ endDate || "结束日期" }}</text>
              <text class="icon">📅</text>
            </view>
          </picker>
        </view>
      </view>
    </view>

    <!-- 导出按钮 -->
    <view class="export-button-section">
      <button
        class="export-btn"
        :class="{ disabled: isExporting }"
        @tap="handleExport"
        :disabled="isExporting"
      >
        <text v-if="isExporting">生成中...</text>
        <text v-else>导出我的订单</text>
      </button>
    </view>
  </view>
</template>

<script>
import { exportOrderList } from "@/common/api/orderList.js";

export default {
  data() {
    return {
      startDate: "",
      endDate: "",
      isExporting: false,
    };
  },

  onLoad() {
    // 设置默认日期范围（最近30天）
    const endDate = new Date();
    const startDate = new Date();
    startDate.setDate(startDate.getDate() - 30);

    this.endDate = this.formatDate(endDate);
    this.startDate = this.formatDate(startDate);
  },

  methods: {
    formatDate(date) {
      return date.toISOString().split("T")[0];
    },

    onStartDateChange(e) {
      this.startDate = e.detail.value;
    },

    onEndDateChange(e) {
      this.endDate = e.detail.value;
    },

    async handleExport() {
      if (this.isExporting) return;

      // 验证必填项
      if (!this.startDate || !this.endDate) {
        uni.showToast({
          title: "请选择时间范围",
          icon: "none",
        });
        return;
      }

      if (new Date(this.startDate) > new Date(this.endDate)) {
        uni.showToast({
          title: "开始日期不能大于结束日期",
          icon: "none",
        });
        return;
      }

      // 获取当前用户信息
      const userInfo = uni.getStorageSync("userInfo");
      if (!userInfo || !userInfo.id) {
        uni.showToast({
          title: "请先登录",
          icon: "none",
        });
        setTimeout(() => {
          uni.reLaunch({
            url: "/pages/login/login",
          });
        }, 1500);
        return;
      }

      this.isExporting = true;

      try {
        // 构建导出参数，包含用户ID
        const exportParams = {
          type: "orders",
          startDate: this.startDate,
          endDate: this.endDate,
          format: "excel",
          customerId: userInfo.id, // 添加用户ID，只导出当前用户的订单
        };

        console.log("导出参数:", exportParams);
        console.log("当前用户:", userInfo.nickName, "ID:", userInfo.id);

        // 调用导出API
        const response = await exportOrderList(exportParams);

        // 检查响应格式
        console.log("导出API响应:", response);

        // 适配两种可能的响应格式
        let responseData = response;
        if (response.httpCode === 200 && response.data) {
          responseData = response.data;
        }

        if (
          responseData &&
          responseData.ok &&
          responseData.data &&
          responseData.data.fileName
        ) {
          // 直接下载文件
          const { fileName, recordCount, fileSize } = responseData.data;
          console.log("生成的文件名:", fileName);
          console.log("导出记录数:", recordCount);
          console.log("文件大小:", fileSize);

          // 显示导出成功信息
          uni.showModal({
            title: "我的订单导出成功",
            content: `成功导出您的 ${recordCount} 条订单记录\n文件大小: ${this.formatFileSize(
              fileSize
            )}\n\n点击确定开始下载文件`,
            showCancel: false,
            confirmText: "开始下载",
            success: () => {
              this.downloadFile(fileName);
            },
          });
        } else {
          console.error("导出响应异常:", response);
          console.error("响应详情:", {
            originalResponse: response,
            processedResponse: responseData,
            hasOk: !!responseData?.ok,
            hasData: !!responseData?.data,
            hasFileName: !!responseData?.data?.fileName,
            fileName: responseData?.data?.fileName,
            message: responseData?.message,
          });

          // 检查是否是无订单的情况
          if (responseData?.data?.recordCount === 0) {
            uni.showModal({
              title: "暂无订单记录",
              content:
                responseData.message ||
                "在选定的时间范围内没有找到您的订单记录，请调整时间范围后重试。",
              showCancel: false,
              confirmText: "知道了",
            });
            return;
          }

          throw new Error(
            responseData?.message || response.message || "导出失败"
          );
        }
      } catch (error) {
        console.error("导出失败:", error);

        let errorMessage = "文件生成失败，请重试";
        if (error.message) {
          errorMessage = error.message;
        } else if (error.data && error.data.message) {
          errorMessage = error.data.message;
        }

        uni.showModal({
          title: "导出失败",
          content: `文件生成失败：${errorMessage}\n\n请检查网络连接或联系管理员。`,
          showCancel: true,
          cancelText: "取消",
          confirmText: "重试",
          success: (res) => {
            if (res.confirm) {
              // 用户选择重试
              setTimeout(() => {
                this.handleExport();
              }, 500);
            }
          },
        });
      } finally {
        this.isExporting = false;
      }
    },

    // 格式化文件大小
    formatFileSize(bytes) {
      if (!bytes || bytes === 0) return "0 B";
      const k = 1024;
      const sizes = ["B", "KB", "MB", "GB"];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
    },

    // 下载文件 - 统一使用复制链接到剪贴板的方式
    downloadFile(fileName) {
      if (!fileName) {
        uni.showToast({
          title: "文件名无效",
          icon: "none",
        });
        return;
      }

      // 使用request.js中的BASE_URL来构建下载链接
      const { BASE_URL } = require("@/common/utils/request.js");
      const downloadUrl = `${BASE_URL}/api/file/download/${fileName}`;
      console.log("下载链接:", downloadUrl);

      // 尝试直接下载（仅在支持的平台上）
      // #ifdef H5
      try {
        const link = document.createElement("a");
        link.href = downloadUrl;
        link.download = fileName;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);

        uni.showToast({
          title: "开始下载文件",
          icon: "success",
        });
        return;
      } catch (error) {
        console.error("H5直接下载失败:", error);
      }
      // #endif

      // 对于小程序和其他平台，使用复制到剪贴板的方式
      uni.setClipboardData({
        data: downloadUrl,
        success: () => {
          uni.showModal({
            title: "文件已生成",
            content: `订单文件已生成完成！\n\n下载链接已复制到剪贴板，请在浏览器中粘贴打开下载。\n\n文件名：${fileName}`,
            showCancel: false,
            confirmText: "知道了",
          });
          console.log("下载链接已复制到剪贴板");
        },
        fail: (error) => {
          console.error("复制到剪贴板失败:", error);
          // 如果复制失败，显示链接让用户手动复制
          uni.showModal({
            title: "请手动下载",
            content: `文件已生成，请复制以下链接到浏览器下载：\n\n${downloadUrl}\n\n文件名：${fileName}`,
            showCancel: false,
            confirmText: "知道了",
          });
        },
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.export-order {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.header {
  background-color: #fff;
  padding: 20upx 30upx;
  border-bottom: 1upx solid #eee;

  .title {
    font-size: 36upx;
    font-weight: bold;
    color: #333;
    text-align: center;
  }
}

.filter-section {
  background-color: #fff;
  margin: 20upx;
  border-radius: 12upx;
  padding: 30upx;

  .filter-item {
    .label {
      font-size: 28upx;
      color: #666;
      margin-bottom: 20upx;
      display: block;
    }

    .date-range {
      display: flex;
      align-items: center;

      .date-picker {
        flex: 1;
        padding: 20upx;
        border: 1upx solid #ddd;
        border-radius: 8upx;
        background-color: #fafafa;
        display: flex;
        justify-content: space-between;
        align-items: center;

        text {
          font-size: 28upx;
          color: #333;
        }

        .icon {
          color: #999;
        }
      }

      .to {
        margin: 0 20upx;
        font-size: 28upx;
        color: #666;
      }
    }
  }
}

.export-button-section {
  padding: 30upx;

  .export-btn {
    width: 100%;
    height: 88upx;
    background: linear-gradient(135deg, #007aff, #5ac8fa);
    border-radius: 12upx;
    color: #fff;
    font-size: 32upx;
    font-weight: bold;
    border: none;
    display: flex;
    align-items: center;
    justify-content: center;

    &.disabled {
      background: #ccc;
      opacity: 0.6;
    }

    &:not(.disabled):active {
      opacity: 0.8;
    }
  }
}
</style>
